package com.ldl.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ldl.servlet.LoginServlet;

/**
 * @author Administrator
 * Author : L.D.L
 * E-mail : 1419485293@qq.com
 * Date : 2020年7月16日下午7:04:55
 */
public class DBHelper {

	private static Logger log1 = LoggerFactory.getLogger(DBHelper.class) ;
	private DBHelper() {
	}
	
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	
	static{
		try {
			Properties config = new Properties();
			config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
			url = config.getProperty("jdbc.url");
			username = config.getProperty("jdbc.username");
			password = config.getProperty("jdbc.password");
			
			String className = config.getProperty("jdbc.driver");
			Class.forName(className);
		} catch (Exception e) {
//			e.printStackTrace();
			log1.debug("{}",e);
			System.exit(0);
		}
	}
	/**
	 * 创建连接对象
	 * @return 连接对象
	 */
	public static Connection getConn(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url ,username ,password);
		} catch (SQLException e) {
//			e.printStackTrace();
			log1.debug("{}",e);
		}
		return conn;
	}
	
	/**
	 * 关闭连接
	 * @param conn
	 * @param state
	 * @param res
	 */
	public static void close(Connection conn, Statement state, ResultSet res){
		try {
			if(res != null){
				res.close();
			}else if(state != null){
				state.close();
			}else if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
//			e.printStackTrace();
			log1.debug("{}",e);
		}
	}
	
	/**
	 * 设置预编译的语句的所有参数
	 * @param pstmt
	 * @param args
	 * @throws SQLException
	 */
	public static void setParams(PreparedStatement ps, Object... args) throws SQLException {
		for (int i = 0; i < args.length; i++) {
			ps.setObject(i+1, args[i]);
		}
	}
}
